<template>
  <div class="wenjuan">
    <div class="item_from">
      <div class="switch">
        <span style="margin-right: 10px">开启健康声明问卷:</span>
        <i-switch true-color="#13ce66" :value="healthQuestionnaireSwitch" size="large" @on-change="toggleJuan" false-color="#ff4949">
          <span slot="open">开启</span>
          <span slot="close">关闭</span>
        </i-switch>
      </div>
      <Button type="success" @click="editSubjectShow=true;isAdd = true">添加题目</Button>
    </div>
    <!--  展示题目列表  -->
    <div v-if="subject_list.length" class="subject_list">
      <div class="subject_item" v-for="item in subject_list" :key="item.id">
        <div class="subject_title">
          <Row type="flex" align="middle">
            <Col span="18">
              <div style="margin-bottom: 10px"><span class="bi" v-if="item.mustAnswer">*</span>{{ item.subjectName }}</div>
              <template v-if="item.subjectType === 1">
                <Radio-group>
                  <Radio v-for="option in item.options" :key="option.name" :label="option.optionName" />
                </Radio-group>
              </template>
              <template v-if="item.subjectType === 2">
                <Checkbox-group>
                  <Checkbox v-for="option in item.options" :key="option.name" :label="option.optionName"/>
                </Checkbox-group>
              </template>
              <template v-if="item.subjectType === 3">
                <Input placeholder="请输入..." style="width: 300px"/>
              </template>
            </Col>
            <Col offset="3" span="3">
              <Button type="primary" @click="updateS(item)" style="background-color: #39f;border-color: #39f">编辑</Button>
              <Button type="error" @click="deleteSubject(item.id)">删除</Button>
            </Col>
          </Row>
        </div>
      </div>
    </div>
    <div v-else style="display: flex;align-items: center;justify-content: center;text-align: center;margin: 40px 0;">
      <div>
        <img src="../../assets/image/nothing.png" alt="">
        <div>暂无问卷</div>
      </div>
    </div>
    <div style="display: flex; justify-content: center" v-if="!(total <= subject_condition.size)"><Page :total="total" @on-change="changePage" :page-size="subject_condition.size" show-elevator/></div>
    <!--  新增修改题目  -->
    <Modal
      width="800"
      v-model="editSubjectShow"
      :title="isAdd ? '新增题目' : '修改题目'"
      @on-cancel="closed"
     >
      <Form ref="formCustom" :model="subjectContent" :rules="ruleCustom" :label-width="85">
        <Form-item label="题目类型:" prop="subjectType">
          <Select :disabled="!isAdd" v-model="subjectContent.subjectType" @on-change="typeChange" style="width:200px" placeholder="请选择题目类型">
            <Option v-for="item in xuanxiang" :value="item.value" :key="item.value + item.name">{{ item.name }}</Option>
          </Select>
        </Form-item>
        <Form-item label="是否必答:" prop="mustAnswer">
          <i-switch true-color="#13ce66" @on-change="switchS" :value="healthQuestionnaireSwitch" size="large" v-model="subjectContent.mustAnswer" false-color="#ff4949">
            <span slot="open">是</span>
            <span slot="close">否</span>
          </i-switch>
        </Form-item>
        <template v-if="subjectContent.subjectType !== 3 && subjectContent.subjectType">
          <Form-item label="题目内容:" prop="subjectName">
            <Input placeholder="请输入题目内容" v-model="subjectContent.subjectName"/>
          </Form-item>
          <Form-item
            v-for="(item, index) in subjectContent.options"
            :key="index"
            :label="'选项' + (index + 1)"
            :prop="'options.' + index + '.optionName'"
            :rules="{required: true, message: '选项' + (index + 1) +'不能为空', trigger: 'blur'}">
            <Row>
              <Col span="13">
                <Input type="text" v-model="item.optionName" placeholder="请输入..."/>
              </Col>
              <Col span="6" offset="1">
                <Checkbox :disabled="!subjectContent.mustAnswer" v-model="item.bookCondition">选择该选项后拒绝预约</Checkbox>
              </Col>
              <Col span="2" offset="1">
                <Button type="error" @click="subjectContent.options.splice(index, 1)">删除</Button>
              </Col>
            </Row>
            <Row v-if="item.luojiTi">
              <Col :span="12" offset="1">{{ item.luojiTi.subjectName }}</Col>
              <Col :span="4" offset="1"><Button type="error" :loading="item.luojiTi.loading" size="small" @click="removeLuoji(item.luojiTi, item)">删除</Button></Col>
            </Row>
          </Form-item>
          <Form-item>
              <Button type="dashed" long @click="handleAdd" icon="plus-round">新增</Button>
              <Button type="dashed" long @click="addLogic" icon="plus-round" style="margin-top: 20px" v-if="subjectContent.subjectType === 1">添加逻辑题目</Button>
          </Form-item>
        </template>
        <template v-if="subjectContent.subjectType === 3">
          <Form-item label="题目内容:" prop="subjectName">
            <Input placeholder="请输入题目内容" v-model="subjectContent.subjectName"/>
          </Form-item>
        </template>
      </Form>
      <div slot="footer">
        <div style="width: 80%;margin: auto">
          <Button type="primary" @click="editSubject" style="background-color: #39f;border-color: #39f" long>完成编辑</Button>
        </div>
      </div>
    </Modal>
    <!--  关联逻辑题目  -->
    <Modal v-model="luoji" title="逻辑题目">
      <div style="display: flex; flex-wrap: wrap; justify-content: center">
        <Radio-group v-model="optionName" @on-change="changeOption">
          <Radio v-for="(item, i) in subjectContent.options" :key="i" :label="item.optionName || '暂无设置'"/>
        </Radio-group>
        <div style="width: 100%;">
          <Select style="width: 80%;display: block;margin: auto" v-model="nextSubjectId">
            <Option-group label="单选">
              <template v-for="item in xuan">
                <Option v-if="item.subjectType === 1"  :value="item.id" :key="item.id">{{ item.subjectName }}</Option>
              </template>
            </Option-group>
            <Option-group label="多选">
              <template v-for="item in xuan">
                <Option v-if="item.subjectType === 2"  :value="item.id" :key="item.id">{{ item.subjectName }}</Option>
              </template>
            </Option-group>
            <Option-group label="单项填空">
              <template v-for="item in xuan">
                <Option v-if="item.subjectType === 3"  :value="item.id" :key="item.id">{{ item.subjectName }}</Option>
              </template>
            </Option-group>
          </Select>
        </div>
      </div>
      <div slot="footer">
        <Button type="warning" @click="() => {this.luoji=false; this.luojiCloase()}">取消</Button><Button type="info" @click="logicConfirm">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
let ruleCustom = {
  subjectName: [
    {required: true, trigger: 'change', message: '题目内容不能为空'}
  ],
  optionName: [
    {required: true, trigger: 'change', message: '选项内容不能为空'}
  ],
  subjectType: [
    {required: true, trigger: 'change', message: '题目类型必选', type:'number'}
  ]
}
let xuanxiang = [
  {name: '单选题', value: 1},
  {name: '多选题', value: 2},
  {name: '单项填空', value: 3}
]
// 现在我要把obj字面量创建里的属性深拷贝（ 属性值是引用类型也要深拷贝 ）
function deepClone(source){
  const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
  for(let keys in source){ // 遍历目标
    if(source.hasOwnProperty(keys)){
      if(source[keys] && typeof source[keys] === 'object'){ // 如果值是对象，就递归一下
        targetObj[keys] = source[keys].constructor === Array ? [] : {};
        targetObj[keys] = deepClone(source[keys]);
      }else{ // 如果不是，就直接赋值
        targetObj[keys] = source[keys];
      }
    }
  }
  return targetObj;
}
export default {
  name: 'Questionnaire',
  props: ['museumId', 'healthQuestionnaireSwitch'],
  data () {
    return {
      allSubjectList: [],
      luoji: false,
      nextSubjectId: null,
      total: 0,
      isAdd: true,
      editSubjectShow: false,
      subject_list: [],
      subject_condition: {
        current: 1,
        orders: [
          {
            asc: true,
            column: ''
          }
        ],
        size: 6,
        subjectName: ''
      },
      subjectContent: {
        mustAnswer: true,
        options: null,
        serialNumber: 0,
        subjectName: '',
        subjectType: null
      },
      // 逻辑题目
      xuan: [],
      ruleCustom,
      xuanxiang,
      optionName: '',
    }
  },
  watch: {
    museumId(newV) {
      this.subjectContent.museumId = newV;
      this.subject_condition.museumId = newV;
      this.getSubject()
    }
  },
  created () {
    this.getAllSubjectList();
    this.subjectContent.museumId = this.museumId;
    this.subject_condition.museumId = this.museumId;
    this.getSubject();
  },
  methods: {
    // 删除逻辑题目
    removeLuoji(item, option) {
      item.loading = true;
      this.subjectContent.options = [...this.subjectContent.options];
      this.$http("/stage/museumSubject/removeLogicSubject", {subjectId: item.id}, 'get', res => {
        if(Number(res.data.code) === 200) {
          delete option.luojiTi;
          option.nextSubjectId = "0";
          this.subjectContent.options = [...this.subjectContent.options];
          this.$Message.success("删除成功!");
        } else {
          item.loading = false;
          this.subjectContent.options = [...this.subjectContent.options];
          this.$Message.error("未知错误!");
        }
      })
    },
    getAllSubjectList() {
      let data = {
        current: 1,
        size: 100,
      }
      if(this.$store.state.museums.length > 1 || this.$store.state.superAdmin == "true") {
        data.museumId = this.museumId;
      }
      this.$http('/stage/museumSubject/getMuseumSubject', data, 'post', res => {
        this.allSubjectList = res.data.data.records;
      })
    },
    switchS(v) {
      if(!v) {
        this.subjectContent.options.forEach(item => {
          item.bookCondition = false;
        })
      }
    },
    changePage(currentPage) {
      this.subject_condition.current = currentPage;
      this.getSubject()
    },
    typeChange() {
      this.subjectContent.mustAnswer = true;
      this.$set(this.subjectContent, "options", [
        {
          'bookCondition': false,
          'nextSubjectId': 0,
          'optionName': ''
        }
      ])
    },
    closed() {
      this.$refs['formCustom'].resetFields();
      if(this.isAdd) {
        this.subjectContent.serialNumber += 1;
      }
      this.$set(this.subjectContent, 'subjectType', '');
      this.$set(this.subjectContent, 'subjectName', '');
      this.$set(this.subjectContent, 'mustAnswer', true);
      this.$set(this.subjectContent, "options", [
        {
          'bookCondition': false,
          'nextSubjectId': 0,
          'optionName': ''
        }
      ])
      this.editSubjectShow = false;
    },
    toggleJuan () {
      this.$http('/stage/museumSubject/enableOrDisableHealthQuestionnaireSwitch', {museumId: this.museumId}, 'get', res => {
        console.log(res)
      })
    },
    getSubject (fn) {
      this.$http('/stage/museumSubject/getMuseumSubject', this.subject_condition, 'post', res => {
        res.data.data.records.forEach(item => {
          item.options.forEach(value => {
            !item.mustAnswer ? value.bookCondition = false : value.bookCondition = !value.bookCondition;
          })
        })
        this.subject_list = res.data.data.records;
        this.subjectContent.serialNumber = res.data.data.records.length + 1
        this.total = res.data.data.total
        fn && fn()
      })
    },
    editSubject () {
      this.$refs['formCustom'].validate((valid) => {
        if (valid) {
          this.isAdd ? this.addSubject() : this.updateSubject()
        } else {
          this.$Message.error('请填写题目信息！');
        }
      })
    },
    handleAdd() {
      this.subjectContent.options.push({
        'bookCondition': false,
        'nextSubjectId': 0,
        'optionName': ''
      });
      this.subjectContent = {...this.subjectContent}
    },
    // 新增题目
    addSubject() {
      let data = deepClone(this.subjectContent);
      data.options.forEach(item => {
        delete item.luojiTi
      })
      data.options = this.getOptions();
      data.museumId = this.museumId;
      if(!(this.$store.state.museums.length > 1 || this.$store.state.superAdmin == "true")) {
        delete data.museumId
      }
      this.$http('/stage/museumSubject/addMuseumSubject', data, 'post', res => {
        if(res.data.code === 200) {
          this.$Message.success('新增题目成功!');
          this.getAllSubjectList();
          this.getSubject(() => {
            this.closed()
          })
        }
      })
    },
    // 删除题目
    deleteSubject(subjectId) {
      this.$Modal.confirm({
        title: '确定删除该题目吗?',
        onOk: () => {
          this.$http('/stage/museumSubject/deleteMuseumSubject', { subjectId }, 'get', res => {
            if(res.data.code === 200) {
              this.getSubject()
              this.$Message.success('删除题目成功!');
            }
          })
        }
      })

    },
    // 修改题目
    updateSubject() {
      let data = deepClone(this.subjectContent);
      data.options.forEach(item => {
        delete item.luojiTi
      })
      data.options = this.getOptions();
      data.museumId = this.museumId;
      if(!(this.$store.state.museums.length > 1 || this.$store.state.superAdmin == "true")) {
        delete data.museumId
      }
      this.$http('/stage/museumSubject/updateMuseumSubject', data, 'post', res => {
        if(res.data.code === 200) {
          this.$Message.success('修改题目成功!');
          this.getSubject(() => {
            this.closed()
          })
        }
      })
    },
    getOptions() {
      let options = deepClone(this.subjectContent.options);
      options.forEach(item => {
        !this.subjectContent.mustAnswer ? item.bookCondition = false : item.bookCondition = !item.bookCondition;
      })
      return options;
    },
    updateS(info) {
      this.isAdd = false;
      this.$set(this, 'subjectContent', deepClone(info));
      this.subjectContent.options.forEach(item => {
        if(item.nextSubjectId && item.nextSubjectId !== '0') {
          let { id, subjectName } = this.allSubjectList.find(v => v.id === item.nextSubjectId);
          item.luojiTi = { id, subjectName, loading: false };
        }
      })
      console.log(this.subjectContent.options)
      this.editSubjectShow = true;
    },

    addLogic() {
      if(this.subjectContent.options.length) {
        let isKong = this.subjectContent.options.every(item => item.optionName && item.optionName.trim() !== '');
        if(isKong) {
          this.luoji = true;
          this.xuan = this.allSubjectList.filter(item => item.id !== this.subjectContent.id);
        } else {
          this.$Message.warning("所有选项不能为空!!!");
        }
      } else {
        this.$Message.warning("请先添加选项");
      }
    },
    logicConfirm() {
      if(!this.optionName) {
        this.$Message.error("请先选择逻辑选项!");
        return;
      }
      if(!this.nextSubjectId) {
        this.$Message.error("逻辑题目不能为空!");
        return
      }
      let option = this.subjectContent.options.find(item => item.optionName === this.optionName);
      option.nextSubjectId = this.nextSubjectId;
      this.subjectContent.options.forEach(item => {
        if(item.nextSubjectId && item.nextSubjectId !== '0') {
          let { id, subjectName } = this.allSubjectList.find(v => v.id === item.nextSubjectId);
          item.luojiTi = { id, subjectName };
        }
      })
      this.luojiCloase()
    },
    luojiCloase() {
      this.nextSubjectId = '';
      this.optionName = '';
      this.luoji = false;
    },
    changeOption() {
      let option = this.subjectContent.options.find(item => item.optionName === this.optionName);
      this.nextSubjectId = option.nextSubjectId;
    }
  }
}
</script>

<style scoped>
  .wenjuan {
    padding: 10px 20px;
  }
  .item_from {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .subject_list {
    margin-top: 20px;
  }
  .bi {
    color: red;
    margin-right: 5px;
  }
  .subject_item {
    margin-bottom: 30px;
  }
</style>
